'use client'

import { useEffect, useMemo } from 'react'
import { useTheme } from 'next-themes'
import { Icon, IconName, MaybeElement } from '@blueprintjs/core'
import { MotionButtonBase } from '@/components/button/MotionButton'
import { Button, Space } from 'antd'
import clsx from 'clsx'

type ThemeType = {
  icon: IconName | MaybeElement
  theme: string
}[]

export const ThemeToggle = () => {
  const { theme, setTheme } = useTheme()

  const changeTheme = (value: string) => {
    setTheme(value)
  }

  const themes: ThemeType = [
    {
      theme: 'light',
      icon: 'flash'
    },
    {
      theme: 'dark',
      icon: 'contrast'
    },
    {
      theme: 'system',
      icon: 'desktop'
    }
  ]

  useEffect(() => {
    if (theme === undefined) {
      setTheme('light')
    }
  }, [theme])

  const changeBtnClsx = (isSelect: boolean) =>
    clsx(
      'data-[focus-visible]:outline-focus pl-1 relative size-5 flex-none rounded-full outline-none transition-colors text-gray-400 hover:text-gray-800 dark:hover:text-gray-300 dark:text-gray-300 dark:ring-white/20',
      isSelect && [
        'text-gray-800',
        'bg-gray-400',
        'dark:bg-gray-200',
        'dark:text-gray-300'
      ]
    )

  const changeIconClsx = (isSelect: boolean) =>
    clsx(
      'text-gray-800 dark:text-gray-300 fill-gray-800 dark:fill-gray-600',
      isSelect && ['dark:hover:fill-gray-400']
    )

  return (
    theme && (
      <div className="hidden md:flex w-20">
        <div className="flex gap-x-1.5 rounded-full bg-gray-300 p-1 ring-1 ring-gray-300 light:ring-inset dark:bg-black/30 dark:ring-white/5 dark:border-gray-500 dark:border-[1px]">
          {themes?.map(item => (
            <button
              key={item.theme}
              type="button"
              onClick={() => changeTheme(item.theme)}
              className={changeBtnClsx(item.theme === theme)}
            >
              <Icon
                icon={item.icon}
                size={12}
                className={changeIconClsx(item.theme !== theme)}
              />
            </button>
          ))}
        </div>
      </div>
    )
  )
}
